import { notification } from 'antd';
import cloneDeep from 'lodash/cloneDeep';
import { getChartData } from '../../../../services/stock_service';
import { GetDateThree, FormatnumberZero } from '../../../../function';

export default {
  namespace: 'forecast',
  state: {
    chartData: [],
  },

  effects: {
    *GetChartData({ payload, callback }, { call, put }) {
      const response = yield call(getChartData, payload);
      if (typeof response === 'undefined') {
        return;
      }
      if (typeof response !== 'undefined' && response.code === 1) {
        const { list } = response;
        list.laterList = [];
        const newDate = Date.parse(list.predictionList[0][list.predictionList[0].length - 1].date);

        for (let i = 1; i < list.predictionList.length; i++) {
          let y = 0;
          list.predictionList[i].find(function(x) {
            if (list.middleDates[i].date2 === x.date) {
              return y;
            }
            y++;
          });

          /* 换算比例 = （(历史预测区域第一根K线涨幅+1)*最新K线收盘价）/历史预测区域第一根K线收盘价 */
          const ratio =
            (((list.predictionList[i][y + 1].closePrice - list.predictionList[i][y].closePrice) /
              list.predictionList[i][y].closePrice +
              1) *
              list.predictionList[0][list.predictionList[0].length - 1].closePrice) /
            list.predictionList[i][y + 1].closePrice;

          list.laterList.push(cloneDeep(list.predictionList[i]).splice(y + 1));

          for (let j = 0; j < list.laterList[list.laterList.length - 1].length; j++) {
            const jb = list.laterList[list.laterList.length - 1][j];
            jb.date = GetDateThree(newDate + 86400000 * (j + 1));
            jb.closePrice = +FormatnumberZero(jb.closePrice * ratio, 2);
            jb.openPrice = +FormatnumberZero(jb.openPrice * ratio, 2);
            jb.high = +FormatnumberZero(jb.high * ratio, 2);
            jb.low = +FormatnumberZero(jb.low * ratio, 2);
          }
        }

        yield put({
          type: 'saveChartData',
          payload: list,
        });

        if (callback) callback(response);
      } else {
        notification.error({
          message: `请求错误`,
        });
        return false;
      }
    },
  },

  reducers: {
    saveChartData(state, action) {
      return {
        ...state,
        chartData: action.payload,
      };
    },
  },
};
